﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StyleMVVM.DependencyInjection;

namespace StyleMVVM.Data
{
	public abstract class BaseDataController<TKey>
	{
		[Import]
		public IDependencyInjectionContainer Container { get; set; }

		protected virtual Task<T> Get<T>(TKey key)
		{
			return GetAdapter<T>().Get(key);
		}

		protected virtual Task<T> Create<T>(T newT)
		{
			return GetAdapter<T>().Create(newT);
		}

		protected virtual Task<T> Update<T>(T updateT)
		{
			return GetAdapter<T>().Update(updateT);
		}

		protected virtual Task Delete<T>(T oldT)
		{
			return GetAdapter<T>().Delete(oldT);
		}

		protected virtual Task Delete<T>(TKey key)
		{
			return GetAdapter<T>().Delete(key);
		}

		protected virtual Task<TResponse> SendDataAccessMessage<TMessage, TResponse>(TMessage message)
		{
			return GetAccessMessenger<TMessage, TResponse>().SendMessage(message);
		}

		protected virtual IDataAccessAdapter<T, TKey> GetAdapter<T>()
		{
			IDataAccessAdapter<T, TKey> returnValue = Container.Locate<IDataAccessAdapter<T, TKey>>();

			if (returnValue == null)
			{
				throw new Exception("Could not locate DataAccessAdapter: " + typeof(IDataAccessAdapter<T, TKey>).FullName);
			}

			return returnValue;
		}

		protected virtual IDataAccessMessenger<TMessage, TResponse> GetAccessMessenger<TMessage, TResponse>()
		{
			IDataAccessMessenger<TMessage, TResponse> returnValue = Container.Locate<IDataAccessMessenger<TMessage, TResponse>>();

			if (returnValue == null)
			{
				throw new Exception("Could not locate DataAccessMessenger: " + typeof(IDataAccessMessenger<TMessage, TResponse>).FullName);
			}

			return returnValue;
		}
	}
}
